

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.annotation.SwStmNoRepeatSubmitBaseController;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.CommomConfirmInfoDTO;
import com.zdkj.subway.stm.dto.out.SwStTicketPettyAddDTO;
import com.zdkj.subway.stm.dvo.SwStmStationDataEntryLogDvo;
import com.zdkj.subway.stm.entity.SwStTicketPettyAdd;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStTicketPettyAddMapper;
import com.zdkj.subway.stm.service.SwStTicketPettyAddService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 车站配票与配备用金
 *
 * @author songtuo
 * @date 2020-07-09 14:14:41
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstticketpettyadd")
@Api(value = "swstticketpettyadd", tags = "车站配票与配备用金管理")
@Slf4j
public class SwStTicketPettyAddController extends SwStmNoRepeatSubmitBaseController {

    private final SwStTicketPettyAddService swStTicketPettyAddService;

    private final SystemUserService systemUserService;
    @Resource
    private SwStTicketPettyAddMapper swStTicketPettyAddMapper;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param swStTicketPettyAdd 车站配票与配备用金
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStTicketPettyAddPage(Page page, SwStTicketPettyAdd swStTicketPettyAdd) {

		String conductorJobNo = swStTicketPettyAdd.getNsJobNo();
        swStTicketPettyAdd.setNsJobNo(null);//先置空，下面的查询才能起作用
		swStTicketPettyAdd.setNsName(null);

        QueryWrapper<SwStTicketPettyAdd> queryWrappers = Wrappers.query(swStTicketPettyAdd);

		
        if(StringUtils.isNotEmpty(swStTicketPettyAdd.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrappers.lambda().eq(SwStTicketPettyAdd::getNsJobNo,conductorJobNo);//报表路径跳转
        }
        if(StringUtils.isEmpty(swStTicketPettyAdd.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrappers.lambda().like(SwStTicketPettyAdd::getNsJobNo,conductorJobNo);//售票员工号模糊匹配
        }

        //QueryWrapper<SwStTicketPettyAdd> queryWrappers = Wrappers.query(swStTicketPettyAdd);
        queryWrappers.orderByDesc("-DEVICE_ATTRIBUTION");
        queryWrappers.orderByDesc("WORKING_START_TIME");
        if (StringUtils.isNotBlank(swStTicketPettyAdd.getWorkingStartTime())&& StringUtils.isNotBlank(swStTicketPettyAdd.getWorkingEndTime())) {
            queryWrappers.between("working_start_time", swStTicketPettyAdd.getWorkingStartTime(), swStTicketPettyAdd.getWorkingEndTime());
        }
        String dateCondition = swStTicketPettyAdd.getWorkingStartTimeDTO();
        String dateConditions = swStTicketPettyAdd.getWorkingEndTimeDTO();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dateCondition)) {
            queryWrappers.lambda().likeRight(SwStTicketPettyAdd::getWorkingStartTime, dateCondition);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dateConditions)) {
            queryWrappers.lambda().likeRight(SwStTicketPettyAdd::getWorkingEndTime, dateConditions);
        }
        SwStTicketPettyAdd swStTicketPettyAddObj = ObjectUtils.getDefaultObj(SwStTicketPettyAdd.class);
        swStTicketPettyAdd.setLineCode(swStTicketPettyAddObj.getLineCode());
        swStTicketPettyAdd.setStationCode(swStTicketPettyAddObj.getStationCode());
        if (StringUtils.isNotBlank(swStTicketPettyAdd.getNsShift())) {
            queryWrappers.eq("ns_shift", swStTicketPettyAdd.getNsShift());
        }
//        else if(StringUtils.isNotBlank(swStTicketPettyAdd.getNsName())){
//            queryWrappers.eq("ns_name", swStTicketPettyAdd.getNsName());
//        }
        else if(StringUtils.isNotBlank(swStTicketPettyAdd.getDeviceOperateNum())){
            queryWrappers.eq("device_operate_num", swStTicketPettyAdd.getDeviceOperateNum());
        }
        if (!SecurityUtils.getUser().getBelongToLine()) {
            //queryWrappers.eq("station_code", SecurityUtils.getUser().getStationCode());
            queryWrappers.lambda().eq(SwStTicketPettyAdd::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrappers.lambda().eq(SwStTicketPettyAdd::getStationCode, SecurityUtils.getUser().getStationCode());
            return R.ok(swStTicketPettyAddService.page(page, queryWrappers));
        } else {
            return R.ok(swStTicketPettyAddService.page(page, Wrappers.query(swStTicketPettyAdd)));
        }
        /*QueryWrapper queryWrapper=new QueryWrapper();
        if (StringUtils.isNotBlank(swStTicketPettyAdd.getWorkingStartTime())&& StringUtils.isNotBlank(swStTicketPettyAdd.getWorkingEndTime())) {
            queryWrapper.between("working_start_time", swStTicketPettyAdd.getWorkingStartTime(), swStTicketPettyAdd.getWorkingEndTime());
        }
        SwStTicketPettyAdd swStTicketPettyAddObj = ObjectUtils.getDefaultObj(SwStTicketPettyAdd.class);
        swStTicketPettyAdd.setLineCode(swStTicketPettyAddObj.getLineCode());
        swStTicketPettyAdd.setStationCode(swStTicketPettyAddObj.getStationCode());
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.eq("station_code", SecurityUtils.getUser().getStationCode());
        }
        if (StringUtils.isNotBlank(swStTicketPettyAdd.getNsShift())) {
            queryWrapper.eq("ns_shift", swStTicketPettyAdd.getNsShift());
        }else if(StringUtils.isNotBlank(swStTicketPettyAdd.getNsName())){
            queryWrapper.eq("ns_name", swStTicketPettyAdd.getNsName());
        }else if(StringUtils.isNotBlank(swStTicketPettyAdd.getDeviceOperateNum())){
            queryWrapper.eq("device_operate_num", swStTicketPettyAdd.getDeviceOperateNum());
        }
        return R.ok(swStTicketPettyAddService.page(page, queryWrapper));*/
    }

    @RequestMapping("/getSwStTicketPettyAdd")
    public R getSwStTicketPettyAdd(@RequestParam Map<String,String> param){
        List<Map<String, Object>> stTicketPettyAdd = swStTicketPettyAddMapper.getSwStTicketPettyAdd(param);
        return R.ok(stTicketPettyAdd);
    }


    /**
     * 通过id查询车站配票与配备用金
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStTicketPettyAddService.getById(id));
    }

    /**
     * 新增车站配票与配备用金
     *
     * @param swStTicketPettyAddDTO 车站配票与配备用金
     * @return R
     */
    @ApiOperation(value = "配票与配备用金录入", notes = "新增车站配票与配备用金")
    //@SysLog("配票与配备用金录入")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_add')")
    public R save(@RequestBody SwStTicketPettyAddDTO swStTicketPettyAddDTO) {
        QueryWrapper queryWrapper=new QueryWrapper();
        PigxUser user = SecurityUtils.getUser();
        queryWrapper.eq("line_code",user.getLineCode());
        queryWrapper.eq("station_code",user.getStationCode());
        queryWrapper.eq("ns_job_no",swStTicketPettyAddDTO.getStTicketPettyAdd().getNsJobNo());
        queryWrapper.eq("ns_shift",swStTicketPettyAddDTO.getStTicketPettyAdd().getNsShift());
        queryWrapper.eq("device_operate_num",swStTicketPettyAddDTO.getStTicketPettyAdd().getDeviceOperateNum());
        queryWrapper.eq("DATE_FORMAT(working_start_time, '%Y-%m-%d')",swStTicketPettyAddDTO.getStTicketPettyAdd().getWorkingStartTime().substring(0,10));
        queryWrapper.eq("del_flag","0");
        int count=swStTicketPettyAddService.count(queryWrapper);
        if(count>0){
            return R.failed(count,swStTicketPettyAddDTO.getStTicketPettyAdd().getNsName()+"在"+swStTicketPettyAddDTO.getStTicketPettyAdd().getWorkingStartTime().substring(0,10)+" 数据已存在！");
        }
        return R.ok(swStTicketPettyAddService.saveSwStTicketPettyAdd(swStTicketPettyAddDTO));
    }

    /**
     * 修改车站配票与配备用金
     *
     * @param swStTicketPettyAddDTO 车站配票与配备用金
     * @return R
     */
    @ApiOperation(value = "配票与配备用金编辑", notes = "修改车站配票与配备用金")
    //@SysLog("配票与配备用金编辑")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_edit')")
    public R updateById(@RequestBody SwStTicketPettyAddDTO swStTicketPettyAddDTO) {
        SwStTicketPettyAdd ticketPettyAdd = swStTicketPettyAddService.getById(swStTicketPettyAddDTO.getStTicketPettyAdd().getId());
        if(ObjectUtil.isNotEmpty(ticketPettyAdd)){
            String submitStatus = ticketPettyAdd.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("line_code",swStTicketPettyAddDTO.getStTicketPettyAdd().getLineCode());
        queryWrapper.eq("station_code",swStTicketPettyAddDTO.getStTicketPettyAdd().getStationCode());
        queryWrapper.eq("ns_job_no",swStTicketPettyAddDTO.getStTicketPettyAdd().getNsJobNo());
        queryWrapper.eq("ns_shift",swStTicketPettyAddDTO.getStTicketPettyAdd().getNsShift());
        queryWrapper.eq("device_operate_num",swStTicketPettyAddDTO.getStTicketPettyAdd().getDeviceOperateNum());
        queryWrapper.eq("DATE_FORMAT(working_start_time, '%Y-%m-%d')",swStTicketPettyAddDTO.getStTicketPettyAdd().getWorkingStartTime().substring(0,10));
        queryWrapper.eq("del_flag","0");
        queryWrapper.ne("id",swStTicketPettyAddDTO.getStTicketPettyAdd().getId());
        int count=swStTicketPettyAddService.count(queryWrapper);
        if(count>0){
            return R.failed(count,swStTicketPettyAddDTO.getStTicketPettyAdd().getNsName()+"在"+swStTicketPettyAddDTO.getStTicketPettyAdd().getWorkingStartTime().substring(0,10)+" 该班次的数据已存在,不允许修改为该售票员的数据！");
        }
        swStTicketPettyAddService.saveTicketPettyDataEntryLog(swStTicketPettyAddDTO,1);
        return R.ok(swStTicketPettyAddService.updateSwStTicketPettyAdd(swStTicketPettyAddDTO));
    }

    /**
     * 通过id查询车站配票与配备用金（主表）历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询车站配票与配备用金（主表）历史记录", notes = "通过id查询车站配票与配备用金（主表）历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<SwStmStationDataEntryLogDvo> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_TICKET_PETTY_ADD));
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                SwStmStationDataEntryLogDvo swStmStationDataEntryLogDvo = new SwStmStationDataEntryLogDvo();
                BeanUtils.copyProperties(x,swStmStationDataEntryLogDvo);
                swStmStationDataEntryLogDvo.setLogInfo(jsonObject);
                LogInfoList.add(swStmStationDataEntryLogDvo);
            });
        }
        //返回json串
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map((SwStmStationDataEntryLog::getLogInfo)).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

    /**
     * 通过记录表id查询具体的车站配票与配备用金详情历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过记录表id查询具体的车站配票与配备用金详情历史记录", notes = "通过记录表id查询具体的车站配票与配备用金详情历史记录")
    @GetMapping("getLogChildById/{id}")
    public R getLogChildById(@PathVariable("id") Integer id) {
        return R.ok(swStmStationDataEntryLogService.mapListTicketPettyAdd(id));
    }


    /**
     * 通过id删除车站配票与配备用金
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除车站配票与配备用金", notes = "通过id删除车站配票与配备用金")
    //@SysLog("通过id删除车站配票与配备用金")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStTicketPettyAddService.deleteCascadeById(id));
    }

    /**
     * 查询日结账单详情
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询车站配票配备用金详情", notes = "通过id查询")
    @GetMapping("/details/{id}" )
    public R getSwStTicketPettyAdd(@PathVariable("id" ) Integer id) {
        return R.ok(swStTicketPettyAddService.queryDetailsByid(id));
    }
    /**
     * 查询车站配票类型
     * @return R
     */
    @ApiOperation(value = "分组查询车站配票类型", notes = "分组查询车站配票类型")
    @GetMapping("/query/ticketType/{id}" )
    public R queryTicketType(@PathVariable Integer id) {
        return R.ok(swStTicketPettyAddService.queryTicketType(id));
    }

    /**
     * 新增车站配票与配备用金
     *
     * @param swStTicketPettyAddDTO 车站配票与配备用金
     * @return R
     */
    @ApiOperation(value = "新增配票与配备用金", notes = "新增车站配票与配备用金")
    //@SysLog("新增配票与配备用金")
    @PostMapping("/addcashticket")
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_add_cash_ticket')")
    public R addCashAndTicket(@RequestBody SwStTicketPettyAddDTO swStTicketPettyAddDTO) {
        SwStTicketPettyAdd ticketPettyAdd = swStTicketPettyAddService.getById(swStTicketPettyAddDTO.getStTicketPettyAdd().getId());
        if(ObjectUtil.isNotEmpty(ticketPettyAdd)){
            String submitStatus = ticketPettyAdd.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        return R.ok(swStTicketPettyAddService.addCashAndTicket(swStTicketPettyAddDTO));
    }

    /**
     * 配票与配用金归还
     *
     * @param swStTicketPettyAddDTO 配票与配用金归还
     * @return R
     */
    @ApiOperation(value = "配票与配用金归还", notes = "配票与配用金归还")
    //@SysLog("配票与配备用金归还")
    @PostMapping("/returncashticket")
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_return_cash_ticket')")
    public R returnCashAndTickt(@RequestBody SwStTicketPettyAddDTO swStTicketPettyAddDTO) {
        String md5 = MD5.create().digestHex(swStTicketPettyAddDTO.toString());
        if (noPass(SecurityUtils.getUser().getId(), "returnSubmit", md5)) {
            return R.failed("请勿重复提交");
        }

        SwStTicketPettyAdd ticketPettyAdd = swStTicketPettyAddService.getById(swStTicketPettyAddDTO.getStTicketPettyAdd().getId());
        if(ObjectUtil.isNotEmpty(ticketPettyAdd)){
            String submitStatus = ticketPettyAdd.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        swStTicketPettyAddService.saveTicketPettyDataEntryLog(swStTicketPettyAddDTO,2);
        return R.ok(swStTicketPettyAddService.returnCashAndTickt(swStTicketPettyAddDTO));
    }
    /**
     * 查询需要确认的数据
     * @param confirmInfoDTO 查询需要确认的数据
     * @return R
     */
    @ApiOperation(value = "查询需要确认的数据", notes = "查询需要确认的数据")
    //@SysLog("查询需要确认的数据")
    @PostMapping("/query/needConfirmData")
    public R queryNeedToConfirmData(@RequestBody CommomConfirmInfoDTO confirmInfoDTO) {
        return R.ok(swStTicketPettyAddService.queryNeedToConfirmData(confirmInfoDTO));
    }

    /**
     * 查询日结账单详情
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id确认车票备用金数据", notes = "通过id确认车票备用金数据")
    @GetMapping("/confirm/{id}" )
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_confirm')")
    public R confirmData(@PathVariable("id" ) Integer id) {
        return R.ok(swStTicketPettyAddService.confirmData(id));
    }

    /**
     * 批量删除子表
     * @param idList
     * @return
     */
    //@SysLog("通过id批量删除车站配票与配备用金")
    @DeleteMapping("/batchCascadeDel")
    @PreAuthorize("@pms.hasPermission('swstticketpettyadd_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id批量删除车站配票与配备用金", notes = "通过id批量删除车站配票与配备用金")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStTicketPettyAdd> list = swStTicketPettyAddService.list(new QueryWrapper<SwStTicketPettyAdd>().lambda().in(SwStTicketPettyAdd::getId, idList));
        //已经确认的数据不能删除
        List<Integer> deleteIds = list.stream().filter(x -> !x.getSubmitStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStTicketPettyAddService::deleteCascadeById);
        return R.ok();
    }

    @ApiOperation(value = "导出车站配票与配备用金", notes = "导出车站配票与配备用金")
    @GetMapping("/export")
    public void export(Page page, SwStTicketPettyAdd swStTicketPettyAdd, HttpServletResponse response) {
        List<SwStTicketPettyAdd> records = swStTicketPettyAddService.page(page, Wrappers.query(swStTicketPettyAdd)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_EQUIPMENT_ATTRIBUTION);
            R<List<SysDictItem>> shifts = systemUserService.getDictByType(StmConstans.STM_CONDUCTOR_SHIFT);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                Map<String, String> shiftsMap = shifts.getData().stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStTicketPettyAdd record : records) {
                    record.setDeviceAttribution(map.get(record.getDeviceAttribution()));
                    record.setNsShift(shiftsMap.get(record.getNsShift()));
                    if(record.getNsMoringNightShift().equals("1")){
                        record.setNsMoringNightShift("早班");
                    }else{
                        record.setNsMoringNightShift("晚班");
                    }

                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("车站配票与配备用金", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStTicketPettyAdd.class).
                    sheet("车站配票与配备用金").doWrite(records);
        } catch (IOException e) {
            log.error("导出车站配票与配备用金失败");
        }
    }

    /**
     * 配票和配备用金通过被合并的数据ID查询合并之前的记录
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过被合并的数据ID查询合并之前的记录", notes = "通过被合并的数据ID查询合并之前的记录")
    @GetMapping("getMergeBeforById/{id}")
    public R getMergeBeforById(@PathVariable("id") Integer id) {
        SwStTicketPettyAdd ticketPettyAdd = swStTicketPettyAddService.getById(id);
        if(ObjectUtil.isNotEmpty(ticketPettyAdd)){
            String isBeMergedId = ticketPettyAdd.getIsBeMergedId();
            String[] split = isBeMergedId.split(",");
            List<SwStTicketPettyAdd> list = swStTicketPettyAddMapper.getList(split);
            return R.ok(list);
        }else {
            return R.failed("无合并数据！");
        }
    }

    @Override
    public RedisTemplate<String, String> redisTemplate() {
        return redisTemplate;
    }
}
